/*
  Copyright (c) 2014 Dimitrij Gester

  "Smart RC TX" is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  "Smart RC TX" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with "Smart RC TX"; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA
*/

package com.codeplex.smartrctx.configurator.communication;

import java.io.IOException;
import java.util.Set;

import com.codeplex.smartrctx.configurator.main.helpers.BluetoothConnector;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

public class BluetoothCommLink extends CommLink {
	private BluetoothAdapter btAdapter;
	private BluetoothDevice targetDevice;
	private BluetoothConnector btConnector;
	BluetoothConnector.BluetoothSocketWrapper socketWrapper;

	// private

	public BluetoothCommLink() throws Exception {
		this.btAdapter = BluetoothAdapter.getDefaultAdapter();
		if (this.btAdapter == null) {
			throw new Exception("no bluetooth adapter available");
		}
	}

	@Override
	public boolean isEnabled() {
		return this.btAdapter.isEnabled();
	}

	@Override
	public void doConnect() throws IOException {
		if (!this.isEnabled())
			return;

		if (this.targetDevice == null)
			return;

		if (this.connected)
			return;

		socketWrapper = this.btConnector.connect();

		
		setInputStream(socketWrapper.getInputStream());
		setOutputStream(socketWrapper.getOutputStream());
		
	}

	@Override
	public void doDisconnect() throws IOException {
		this.socketWrapper.close();
		this.socketWrapper = null;
	}

	@Override
	public void setCommTarget(String device) {
		try {
			this.disconnect();
		} catch (IOException e) {
		}

		this.targetDevice = null;
		if (BluetoothAdapter.checkBluetoothAddress(device)) {
			BluetoothDevice d = this.btAdapter.getRemoteDevice(device);
			this.targetDevice = d;
		}
		this.btConnector = new BluetoothConnector(this.targetDevice, false, this.btAdapter, null);

	}

	public Set<BluetoothDevice> getAvailablePorts() {
		return this.btAdapter.getBondedDevices();
	}

}
